import 'package:built_collection/built_collection.dart';
import 'package:equatable/equatable.dart';
import 'package:learning_content_admin_pannel.core/core/domain/entities/learning_content/lexical_item/lexical_item.dart';
import 'package:learning_content_admin_pannel.core/core/domain/helpers/lexical_item_comparators.dart';
import 'package:learning_content_admin_pannel.core/core/domain/utils/math.dart';

part 'result.dart';

abstract class HandleLearningContentOuterUpdate {
  LearningContentOuterUpdateHandlingResult call({
    required BuiltMap<String, LexicalItem> lexicalItemMap,
  });
}

class HandleLearningContentOuterUpdateImpl implements HandleLearningContentOuterUpdate {
  const HandleLearningContentOuterUpdateImpl();

  @override
  LearningContentOuterUpdateHandlingResult call({
    required BuiltMap<String, LexicalItem> lexicalItemMap,
  }) {
    final phrasalVerbs = lexicalItemMap.values.whereType<PhrasalVerb>().toBuiltList();

    final comparators = [
      comparePhrasalVerbsByFrequency,
      compareLexicalItemsTitleAlphabetically,
    ];

    final sortedPhrasalVerbs = phrasalVerbs.rebuild((phrasalVerbs) {
      phrasalVerbs.sort((firstPhrasalVerb, secondPhrasalVerb) {
        return combinedComparator(
          first: firstPhrasalVerb,
          second: secondPhrasalVerb,
          comparators: comparators,
        );
      });
    });

    final result = LearningContentOuterUpdateHandlingResult(
      sortedPhrasalVerbs: sortedPhrasalVerbs,
    );

    return result;
  }
}
